package com.diwu.diwuoj.judge;

import cn.hutool.json.JSONUtil;
import com.diwu.diwuoj.common.ErrorCode;
import com.diwu.diwuoj.exception.BusinessException;
import com.diwu.diwuoj.judge.codesandbox.CodeSandBoxFactory;
import com.diwu.diwuoj.judge.codesandbox.CodeSandbox;
import com.diwu.diwuoj.judge.codesandbox.model.CodeSandboxProxy;
import com.diwu.diwuoj.judge.codesandbox.model.ExecuteCodeRequest;
import com.diwu.diwuoj.judge.codesandbox.model.ExecuteCodeResponse;
import com.diwu.diwuoj.judge.strategy.JudgeContext;
import com.diwu.diwuoj.judge.strategy.JudgeStrategy;
import com.diwu.diwuoj.model.dto.question.JudgeCase;
import com.diwu.diwuoj.judge.codesandbox.model.JudgeInfo;
import com.diwu.diwuoj.model.entity.Question;
import com.diwu.diwuoj.model.entity.QuestionSubmit;
import com.diwu.diwuoj.model.enums.QuestionSubmitStatusEnum;
import com.diwu.diwuoj.service.QuestionService;
import com.diwu.diwuoj.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description  判题模块的服务
 * @Author diwu
 * @Date 2024/7/1
 */
@Service
public class JudgeServiceImpl implements JudgeService {
    @Resource
    public QuestionSubmitService questionSubmitService;

    @Resource
    public QuestionService questionService;

    @Resource
    public JudgeManager judgeManager;


    @Value("${codesandbox.type}")
    public String type;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        //1）传入题目的提交 id，获取到对应的题目、提交信息（包含代码、编程语言等）
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if(questionSubmit == null){
            throw  new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交的信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        if(question == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目的信息不存在");
        }
        //2）如果题目提交状态不为等待中，就不用重复执行了
        if(!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目不处于等待中");
        }
        //3）更改判题（题目提交）的状态为 “判题中”，防止重复执行，也能让用户即时看到状态
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目的更新的状态出错");
        }
        //4）调用沙箱，获取到执行结果
        // 这两段代码都是底层都是实现了CodeSandbox 的接口 所以下面的方式知识换了一种引用的方式
        CodeSandbox codeSandbox = CodeSandBoxFactory.newInstance(type);
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        //获取输入的Json字符串用例
        String judgeCaseStr = question.getJudgeCase();
        //因为从数据库中获取的是Json字符串，所以需要将其转换为对应的java 对象的列表
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(questionSubmit.getCode())
                .language(questionSubmit.getLanguage())
                .inputList(inputList).build();
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
        List<String> outputList = executeCodeResponse.getOutputList();
        //5）根据沙箱的执行返回结果，设置题目的判题状态和信息
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
        // 6) 修改数据库中的判题的结果
       questionSubmitUpdate = new QuestionSubmit();
       questionSubmitUpdate.setId(questionSubmitId);
       questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
       questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
       update = questionSubmitService.updateById(questionSubmitUpdate);
       if(! update){
           throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新错误");
       }
       QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionId);
       return questionSubmitResult;
    }
}
